package top.dimples.controller.api;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.expression.Ids;
import springfox.documentation.annotations.ApiIgnore;
import top.dimples.common.ApiResponse;
import top.dimples.common.JWTUser;
import top.dimples.common.NoticeStatus;
import top.dimples.model.Notice;
import top.dimples.service.NoticeService;
import top.dimples.vo.common.PageResult;
import top.dimples.vo.common.PageVO;
import top.dimples.vo.notice.NoticeListVO;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Dimples_Yj
 * @package top.dimples.controller.api
 * @date 2021/12/20
 */
@Api(tags = "通知消息模块")
@Slf4j
@RestController
@RequestMapping("/api/notice")
public class NoticeController {

    @Autowired
    private NoticeService noticeService;

    @ApiOperation(value = "获取用户所有的消息通知")
    @GetMapping("/list")
    public ApiResponse getUserNotice(@ApiIgnore JWTUser jwtUser, PageVO pageVO) {
        // 1、分页查出消息通知
        Page<Notice> page = noticeService.page(
                new Page<>(pageVO.getPageNum(), pageVO.getPageSize()),
                new LambdaQueryWrapper<Notice>()
                        .eq(Notice::getUserId, jwtUser.getId())
                        .orderByDesc(Notice::getCreateTime)
        );
        List<String> noticeIds = page.getRecords().stream().map(Notice::getId).collect(Collectors.toList());
        // 2、转换成 VO 返回给前端
        IPage<NoticeListVO> noticePageList = page.convert(notice -> Convert.convert(NoticeListVO.class, notice));
        List<NoticeListVO> list = noticePageList.getRecords().stream().peek(noticeListVO -> noticeListVO.setStatusName(NoticeStatus.fromCode(noticeListVO.getStatus()).getMessage())).collect(Collectors.toList());
        noticePageList.setRecords(list);
        // 3、获取之后把未读的改成已读
        noticeService.update(new LambdaUpdateWrapper<Notice>().set(Notice::getStatus,NoticeStatus.READ.getCode()).in(Notice::getId, noticeIds).eq(Notice::getStatus,NoticeStatus.UNREAD.getCode()));
        return ApiResponse.ofSuccess(PageResult.startPage(page));
    }

}
